package com.app.servlet;

import com.app.util.DateUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 师晓峰
 * @version V1.0
 * @date 2023/9/21 23:20
 * @Description:
 * 上传图片功能
 */
public class ImageUploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        // 获取前端创建的文件
        FileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
        // 获取到当前部署的项目根路径
//        String root = req.getSession().getServletContext().getRealPath("");
        String root = "D:/SSM_Java/movie/src/main/webapp";
        // 部署后的路径

        try {
            List<FileItem> list = upload.parseRequest(req);
            for(FileItem fileItem : list){
                // 重新定义文件名
                String imageName = DateUtil.getCurrentDateStr();
                // 当前时间文件
                String newPath = "/upload/" + imageName+"."+fileItem.getName().split("\\.")[1];
                File file = new File(root+newPath);
                fileItem.write(file);
                // 输出一个路径
                PrintWriter out = resp.getWriter();
                out.println("<script>parent.setImage('"+newPath+"');document.write('上传成功');</script>");
                out.flush();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
